//
//  HomeTableViewController.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/7.
//  Copyright © 2015年 hzj. All rights reserved.
//

 let HZJNormalCellID = "HZJNormalCellID"
 let HZJRetweetedCellID = "HZJRetweetedCellID"


import UIKit
import SVProgressHUD

class HomeTableViewController: BasicViewController {

    
    ///微博的数据模型
    private lazy var statusesListViewModel = StatusesListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        if !UserAccountViewModel.sharedUserAccountViewModel.isLogin {
            visitorView?.setUIMessage(true, imageName: "visitordiscover_feed_image_smallicon", text: "清风拂面，再回首，难忆往昔；聚聚离离，欢欢乐乐，皆默然")
            return
        }
        
        //注册cell
        tableView.registerClass(HZJNormalCell.self, forCellReuseIdentifier: HZJNormalCellID)
        tableView.registerClass(HZJRetweetedCell.self, forCellReuseIdentifier: HZJRetweetedCellID)
        //预估行高
        tableView.estimatedRowHeight = 300
//        tableView.rowHeight = 300
        
        //取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        loadData()
        
        //添加下拉刷新控件
        refreshControl = HZJRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
//        let tishiView = UIView()
//        refreshControl?.addSubview(tishiView)
        //添加上拉刷新控件
        tableView.tableFooterView = pullUpView

    }
    
    //MARK:-懒加载
    //向上拉时的控件
    private lazy var  pullUpView:UIActivityIndicatorView = {
        let fv = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        fv.color = UIColor.darkGrayColor()
        return fv
    }()
    //刷新微博数的控件
    private lazy var StatusesLable:UILabel = {
        let sv = UILabel(title: nil, color: UIColor.brownColor(), fontSize: 17)
        sv.textAlignment = NSTextAlignment.Center
        sv.backgroundColor = UIColor.orangeColor()
        //加入导航栏中
        self.navigationController?.navigationBar.insertSubview(sv, atIndex: 0)
        return sv
    }()
    //设置刷新微博数的控件
    private func setTheStatusesLable(count:Int) {
//        let title  = count != 0  ? "刷新了\(count)条微博":"无新微博"
        let w :CGFloat = UIScreen.mainScreen().bounds.width
        let h :CGFloat = 44//0.5 * (self.navigationController?.navigationBar.bounds.height)!
        print(self.navigationController?.navigationBar.bounds.height)
        StatusesLable.text = count != 0  ? "刷新了\(count)条微博":"无新微博"
        StatusesLable.frame = CGRectMake(0, -2 * h, w, h)
        
        UIView.animateWithDuration(1.5, animations: { () -> Void in
            self.StatusesLable.frame = CGRectMake(0,h, w, h)
            }) { (_) -> Void in
                UIView.animateWithDuration(1.5, animations: { () -> Void in
                    self.StatusesLable.frame = CGRectMake(0, -2 * h, w, h)
                })
        }
    }
    
    
    /// 加载数据
     func loadData(){
        self.refreshControl?.beginRefreshing()
        statusesListViewModel.loadTheData(pullUpView.isAnimating()).subscribeNext({ (result) -> Void in
            let count = (result as! NSNumber).integerValue
            self.setTheStatusesLable(count)
            }, error: { (error) -> Void in
                printLog(error)
               self.refreshControl?.endRefreshing()
                self.pullUpView.stopAnimating()
                SVProgressHUD.showErrorWithStatus("网络错误")
            }) { () -> Void in
                self.refreshControl?.endRefreshing()
                self.pullUpView.stopAnimating()
                //刷新
                self.tableView.reloadData()
        }
    }
      override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

// MARK: - Table view data source

extension HomeTableViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusesListViewModel.statusesList.count
        
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //取模型(StatusesViewModel类型)
        let statuesViewModel = statusesListViewModel.statusesList[indexPath.row] as! StatusesViewModel
        
        let cell = tableView.dequeueReusableCellWithIdentifier(statuesViewModel.cellID, forIndexPath: indexPath) as! HZJCell
        cell.statusesViewModel = statuesViewModel
        
        //当是最后一个cell，并且未刷新时，进行下拉刷新
        if indexPath.row == statusesListViewModel.statusesList.count - 1  && !pullUpView.isAnimating()
        {
            pullUpView.startAnimating()
            //刷新数据
            loadData()
        }
        
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        // 0. 获得模型
        let viewModel = statusesListViewModel.statusesList[indexPath.row] as! StatusesViewModel
        // 1. 判断视图模型的行高是否为0，如果不为0，表示行高已经缓存
        if viewModel.rowHeight > 0 {
//            printLog("返回缓存行高")
            return viewModel.rowHeight
        }
        
        // 2. 获得 cell，不能使用 indexPath 的方法，否则会出现死循环
        let cell = tableView.dequeueReusableCellWithIdentifier(viewModel.cellID) as! HZJCell
        
        // 3. 记录行高
        viewModel.rowHeight = cell.calculateTheCellHeight(viewModel)
        
        return viewModel.rowHeight

    }
    
    
}
